package com.bzkj.common.utils.http;

import com.alibaba.fastjson2.JSON;
import com.bzkj.common.domain.TmsResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @projectName: prt-wms
 * @package: com.bzkj.common.utils.http
 * @className: TmsHttpUtils
 * @description: TMS请求工具类
 * @author: C1309
 * @createDate: 2024年12月06日
 * @version: v1.0
 */
@Component
public class TmsHttpUtils {
    private static final CloseableHttpClient HTTP_CLIENT;
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    // 初始化 HTTP 客户端，使用连接池确保线程安全
    static {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(100); // 最大连接数
        connectionManager.setDefaultMaxPerRoute(20); // 每个路由的最大连接数
        HTTP_CLIENT = HttpClients.custom().setConnectionManager(connectionManager).build();
    }

    // 从配置文件中读取请求头内容
    @Value("${tms.sourceSystem}")
    private String sourceSystem;

    @Value("${tms.targetSystem}")
    private String targetSystem;

    @Value("${tms.serviceName}")
    private String serviceName;

    @Value("${tms.contentType}")
    private String contentType;

    @Value("${tms.baseUrl}")
    private String baseUrl;

    /**
     * 发送 POST 请求
     *
     * @param path        请求路径
     * @param requestBody 请求体，JSON 字符串
     * @return 响应内容，解析为 Map
     * @throws IOException IO 异常
     */
    public TmsResponse post(String path, String requestBody) throws IOException {

        // 创建 HttpClient
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(baseUrl);
            httpPost.setHeader("SourceSystem", sourceSystem);
            httpPost.setHeader("TargetSystem", targetSystem);
            httpPost.setHeader("ServiceName", serviceName);
            httpPost.setHeader("Content-Type", contentType);
            httpPost.setHeader("PathString", path);

            // 设置请求体
            StringEntity entity = new StringEntity(requestBody, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

                // 使用 FastJSON 2 将响应映射为实体类
                return JSON.parseObject(responseBody, TmsResponse.class);
            }
        }
    }

    /**
     * 发送 GET 请求
     *
     * @param path        请求路径
     * @param queryParams 请求体，JSON 字符串
     * @return 响应内容，解析为 Map
     * @throws IOException IO 异常
     */
    public HashMap get(String path, HashMap<String,String> queryParams) throws Exception {

        // 创建 HttpClient
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 使用 URIBuilder 构建 URL 和查询参数
            URIBuilder uriBuilder = new URIBuilder(baseUrl);

            // 添加查询参数
            if (queryParams != null && !queryParams.isEmpty()) {
                for (Map.Entry<String, String> entry : queryParams.entrySet()) {
                    uriBuilder.addParameter(entry.getKey(), entry.getValue());
                }
            }

            // 构建 URI
            URI uri = uriBuilder.build();

            // 创建 HttpGet 请求
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader("SourceSystem", sourceSystem);
            httpGet.setHeader("TargetSystem", targetSystem);
            httpGet.setHeader("ServiceName", serviceName);
            httpGet.setHeader("Content-Type", contentType);
            httpGet.setHeader("PathString", path);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                // 获取响应体内容
                String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

                // 将响应体转换为 HashMap
                return OBJECT_MAPPER.readValue(responseBody, HashMap.class);
            }
        }
    }
}
